/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;

import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import util.ControlaConexao;

/**
 *
 * @author Ronei
 */
@ManagedBean
public class RelatorioBean implements Serializable {

    public void emitirRelatorio() throws Exception {
        try {
            
            FacesContext fc = FacesContext.getCurrentInstance();
            ExternalContext contexto = fc.getExternalContext();
            HttpServletResponse response = (HttpServletResponse) contexto.getResponse();
            
            String caminho = contexto.getRealPath("/WEB-INF/report/report.jasper");

            
           

            JasperReport relatorio = (JasperReport) JRLoader
                    .loadObjectFromFile(caminho);
            HashMap parametros = new HashMap();
             JasperPrint relatorioPronto =  JasperFillManager
                    .fillReport(caminho, parametros, ControlaConexao
                     .getInstance().getConexao());
             
             contexto.responseReset();
             contexto.setResponseContentType("application/pdf");
             
             OutputStream saida = response.getOutputStream();

            
           JasperExportManager.exportReportToPdfStream(relatorioPronto, saida);
           
           saida.close();
           
           fc.responseComplete();
           

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
